package com.xindaoapp.happypet.fragments;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.longevitysoft.android.xml.plist.PListXMLHandler;
import com.longevitysoft.android.xml.plist.PListXMLParser;
import com.longevitysoft.android.xml.plist.domain.Dict;
import com.longevitysoft.android.xml.plist.domain.PList;
import com.longevitysoft.android.xml.plist.domain.PListObject;
import com.xindao.photonics.fragments.manager.BaseFragment;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.AddressDetailInfo;
import com.xindaoapp.happypet.bean.AddressInfo;
import com.xindaoapp.happypet.bean.ExpressPriceInfo;
import com.xindaoapp.happypet.entry.OrderInfo;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 填写订单
 * 
 * @author chenghao
 * 
 */
public class WriteOrderFragment extends BaseFragment {
    private String addressID;
    private int province;
    /** 订单总价 */
    private float totalPrice;

    /** 快递总价 */
    private float expressPrice;

    private TextView time;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.layout_write_order, container, false);
    }

    @Override
    protected void initViews(View view) {
        super.initViews(view);
        // totalPrice = getArguments().getFloat(Constants.KEY_PRODUCT_PRICE);
        totalPrice = Constants.ALLPRICE;
        activityRootView = getView().findViewById(R.id.root_layout);
    }

    @Override
    protected void initEvents() {
        super.initEvents();
        getView().findViewById(R.id.r_address).setOnClickListener(mOnClickListener);
        getView().findViewById(R.id.inventory).setOnClickListener(mOnClickListener);
        getView().findViewById(R.id.clearing).setOnClickListener(mOnClickListener);
        getView().findViewById(R.id.r_dis).setOnClickListener(mOnClickListener);
        time = (TextView) getView().findViewById(R.id.time);
        bottom = (RelativeLayout) getView().findViewById(R.id.bottom);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
    }

    private TextView tv1;
    private TextView tv2;
    private TextView tv3;
    private Button ok;
    private AlertDialog dialog;
    private String s = "送货时间：工作日和周末皆可";
    private ImageView close;
    private final OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.r_address:
                    Bundle bundle1 = new Bundle();
                    bundle1.putBoolean("isShowTopBar", false);
                    startFragment(new ConsigneeFragment(), bundle1);
                    break;
                case R.id.inventory:
                    Bundle bundle = new Bundle();
                    bundle.putBoolean(Constants.KEY_ONLY_SHOW_PRODUCT, true);
                    bundle.putString(Constants.KEY_RECID, Constants.REC_ID);
                    startFragment(new ShoppingCartFragment(), bundle);
                    break;
                case R.id.clearing:
                    if (checkLegal()) {
                        pay();
                    }
                    break;
                case R.id.r_dis:
                    AlertDialog.Builder builder = new Builder(getActivity());
                    View view = View.inflate(getActivity(), R.layout.dialog_choose_time, null);
                    tv1 = (TextView) view.findViewById(R.id.tv1);
                    tv2 = (TextView) view.findViewById(R.id.tv2);
                    tv3 = (TextView) view.findViewById(R.id.tv3);
                    ok = (Button) view.findViewById(R.id.ok);
                    ok = (Button) view.findViewById(R.id.ok);
                    close = (ImageView) view.findViewById(R.id.close);

                    tv1.setOnClickListener(new ChooseTimeListener());
                    tv2.setOnClickListener(new ChooseTimeListener());
                    tv3.setOnClickListener(new ChooseTimeListener());
                    ok.setOnClickListener(new ChooseTimeListener());
                    close.setOnClickListener(new ChooseTimeListener());

                    dialog = builder.create();
                    // dialog.setView(view);
                    tv1.setSelected(true);
                    dialog.show();
                    dialog.getWindow().setContentView(view);
                    dialog.setOnCancelListener(new OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            dialog.dismiss();
                        }
                    });
                    break;
                default:
                    break;
            }
        }
    };

    private final class ChooseTimeListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv1:
                    tv1.setSelected(true);
                    tv2.setSelected(false);
                    tv3.setSelected(false);
                    break;
                case R.id.tv2:
                    tv1.setSelected(false);
                    tv2.setSelected(true);
                    tv3.setSelected(false);
                    break;
                case R.id.tv3:
                    tv1.setSelected(false);
                    tv2.setSelected(false);
                    tv3.setSelected(true);
                    break;
                case R.id.ok:
                    if (tv1.isSelected()) {
                        s = "送货时间：工作日和周末皆可";
                    }
                    if (tv2.isSelected()) {
                        s = "送货时间：仅工作日送货";
                    }
                    if (tv3.isSelected()) {
                        s = "送货时间：仅周末送货";
                    }
                    time.setText(s);
                    dialog.dismiss();
                    break;
                case R.id.close:
                    dialog.dismiss();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 监听软键盘弹出还是隐藏，处理底部导航显示或隐藏
     */
    private final OnGlobalLayoutListener mOnGlobalLayoutListener = new OnGlobalLayoutListener() {
        private int preHeight = 0;
        private boolean isShowKeyboard = false;

        @Override
        public void onGlobalLayout() {
            int heightDiff =
                    activityRootView.getRootView().getHeight() - activityRootView.getHeight();
            if (preHeight == heightDiff) {
                return;
            }
            preHeight = heightDiff;
            if (heightDiff > 100) {
                isShowKeyboard = !isShowKeyboard;
                if (isShowKeyboard)
                    bottom.setVisibility(View.VISIBLE);
                else
                    bottom.setVisibility(View.GONE);
            }
        }
    };


    /**
     * 计算快递总价
     */
    private List<ExpressPriceInfo> calExpressPrice() {
        List<ExpressPriceInfo> list = new ArrayList<ExpressPriceInfo>();
        PListXMLHandler handler = new PListXMLHandler();
        PListXMLParser parser = new PListXMLParser();
        parser.setHandler(handler);
        try {
            parser.parse(getActivity().getAssets().open("express_prices.plist"));
            PList actualPList = ((PListXMLHandler) parser.getHandler()).getPlist();
            Dict root = (Dict) actualPList.getRootElement();
            Map<String, PListObject> p = root.getConfigMap();

            Iterator<String> i = p.keySet().iterator();

            while (i.hasNext()) {
                ExpressPriceInfo info = new ExpressPriceInfo();
                String key = i.next();
                List<com.longevitysoft.android.xml.plist.domain.String> provinceRoot =
                        (List<com.longevitysoft.android.xml.plist.domain.String>) p.get(key);
                info.key = Integer.parseInt(key);
                info.firstWeight = Integer.parseInt(provinceRoot.get(0).getValue());
                info.increaseWeight = Integer.parseInt(provinceRoot.get(1).getValue());
                list.add(info);
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void pay() {
        getMoccaApi().addOrder(UserState.getUserUid(), addressID, Constants.REC_ID,
                String.valueOf(totalPrice), String.valueOf(expressPrice),
                ((EditText) getView().findViewById(R.id.message)).getText().toString(), s,
                new IRequest<OrderInfo>() {

                    @Override
                    public void request(OrderInfo t) {
                        if (null == getActivity()) {
                            return;
                        }
                        if (t == null || TextUtils.isEmpty(t.order_sn)) {
                            Toast.makeText(getActivity(), "订单提交失败，请重试！", Toast.LENGTH_SHORT).show();
                        } else {
                            Intent intent = new Intent(Constants.DELETE_CART);
                            intent.putExtra("goods_number", 0);
                            getActivity().sendBroadcast(intent);

                            Bundle bundle = new Bundle();
                            bundle.putString(Constants.KEY_ORDER_TITLE, Address.tittle);
                            bundle.putString(Constants.KEY_ORDER_NUMBER, t.order_sn);
                            bundle.putFloat(Constants.KEY_ORDER_TOTAL_PRICE,
                                    Float.valueOf(t.order_amount));// 改成服务器返回订单总金额otalPrice+
                                                                   // expressPrice
                            startFragmentAndClearStack(new OrderSuccessFragment(), bundle);
                        }
                    }
                });
    }

    /**
     * 验证是否可以提交订单
     * 
     * @return
     */
    private boolean checkLegal() {
        if (TextUtils.isEmpty(addressID)) {
            Toast.makeText(getActivity(), "未获取到收件人地址，请设置!!!", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected void onLoadData() {
        super.onLoadData();
        getMoccaApi().getDefaultAddress(UserState.getUserUid(), new IRequest<AddressDetailInfo>() {

            @Override
            public void request(AddressDetailInfo t) {
                if (null == getActivity()) {
                    return;
                }
                if (null != t) {
                    addressID = t.address_id;
                    province = t.province;
                    ((TextView) getView().findViewById(R.id.name)).setText(t.username);
                    ((TextView) getView().findViewById(R.id.phone_number)).setText(t.mobile);
                    ((TextView) getView().findViewById(R.id.address)).setText(t.address);
                    // resetExpressPrice();
                    loadFreight(province);
                } else {
                    onDataArrived(true);
                    ((TextView) getView().findViewById(R.id.name)).setText("未设置收货地址");
                    ((TextView) getView().findViewById(R.id.phone_number)).setText("");
                    ((TextView) getView().findViewById(R.id.address)).setText("");
                    ((TextView) getView().findViewById(R.id.total_price)).setText(String.format(
                            getString(R.string.handle_total),
                            CommonUtil.transitionToFloat(totalPrice)));
                }
            }
        });
    }

    /**
     * 加载运费
     */
    private void loadFreight(int province) {
        getMoccaApi().getFreight(Constants.REC_ID, province, new IRequest<Float>() {

            @Override
            public void request(Float t) {
                expressPrice = t;
                ((TextView) getView().findViewById(R.id.express_price)).setText("￥"
                        + CommonUtil.transitionToFloat(t));
                ((TextView) getView().findViewById(R.id.total_price)).setText(String.format(
                        getString(R.string.handle_total),
                        CommonUtil.transitionToFloat(t + totalPrice)));
                onDataArrived(true);
            }
        });
    }

    List<ExpressPriceInfo> priceInfos;
    private RelativeLayout bottom;
    private View activityRootView;

    /*
     * private void resetExpressPrice() { if (null == priceInfos) { priceInfos = calExpressPrice();
     * } // 计算运费 for (int i = 0; i < priceInfos.size(); i++) { ExpressPriceInfo info =
     * priceInfos.get(i); if (info.key == province) { expressPrice = info.firstWeight +
     * (getArguments().getInt(Constants.KEY_SHOPPING_CART_WEIGHT) - 1) info.increaseWeight;
     * totalPrice = expressPrice + getArguments().getFloat(Constants.KEY_PRODUCT_PRICE); ((TextView)
     * getView().findViewById(R.id.express_price)).setText(CommonUtil
     * .transitionToFloat(expressPrice)); ((TextView)
     * getView().findViewById(R.id.total_price)).setText(String.format(
     * getString(R.string.handle_total), CommonUtil.transitionToFloat(totalPrice))); break; } } }
     */

    @Override
    protected void onFragmentResult(Bundle bundle) {
        super.onFragmentResult(bundle);
        AddressInfo info = (AddressInfo) bundle.getSerializable(Constants.KEY_CONSIGNEE);
        addressID = info.address_id;
        int parseIntProvince = 0;
        try {
            parseIntProvince = Integer.parseInt(info.province);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        province = parseIntProvince;
        ((TextView) getView().findViewById(R.id.name)).setText(info.username);
        ((TextView) getView().findViewById(R.id.phone_number)).setText(info.mobile);
        ((TextView) getView().findViewById(R.id.address)).setText(info.address);
        // resetExpressPrice();
        loadFreight(province);
    }

    @Override
    protected String getTitleName() {
        return "填写订单";
    }

    @Override
    protected boolean showRightView() {
        return false;
    }

}
